package com.zm.controller;

import com.alibaba.fastjson.JSON;
import com.zm.pojo.AppInfo;
import com.zm.pojo.AppVersion;
import com.zm.pojo.BackendUser;
import com.zm.pojo.DataDictionary;
import com.zm.service.AppInfoService;
import com.zm.service.AppVersionService;
import com.zm.service.BackendUserService;
import com.zm.service.DataDictionaryService;
import com.zm.tools.PageDto;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 超级管理员控制类
 * Created by Administrator on 2018/9/13.
 */
@Controller
@RequestMapping("/bu")
public class BackendUserController {
    private Logger logger=Logger.getLogger(BackendUserController.class);
    @Resource
    private BackendUserService backendUserService;
    @Resource
    private AppVersionService appVersionService;

    @Resource
    private AppInfoService appInfoService;
    @Resource
    private DataDictionaryService dictionaryService;
    @RequestMapping("/")
    public String index(){

        return "backenduser/beulogin.jsp";
    }

    /**
     * 超级管理员登录
     * @param usercode
     * @param userpasswrod
     * @param session
     * @return
     */
    @RequestMapping("/login")
    public String login(@RequestParam("usercode") String usercode,
                        @RequestParam("userpassword") String userpasswrod,
                        HttpSession session){

        BackendUser user=backendUserService.login(usercode,userpasswrod);
        if (user==null){
            logger.info("登录失败！");
            return "backenduser/beulogin";
        }
        logger.info("登录成功："+user);
        session.setAttribute("user",user);
        return InternalResourceViewResolver.REDIRECT_URL_PREFIX+"/bu/showappinfo";
    }

    /**
     * 超级管理员退出登录
     * @param session
     * @return
     */
    @RequestMapping("/loginout")
    public String dologinout(HttpSession session){
        //移除session中的username
        session.removeAttribute("username");
        //销毁session对象
        session.invalidate();
        logger.info("用户已退出登录！");
        return "backenduser/beulogin";
    }

    /**
     * 查询状态相关信息
     * @param pagenum
     * @param model
     * @param appInfo
     * @return
     */
    @RequestMapping("/showappinfo")
    public String doselectappinfo(String pagenum,
                                  Model model,
                                  @RequestParam(value = "appInfo",required = false) AppInfo appInfo){
        PageDto dto=appInfoService.selectByStatus(pagenum,appInfo);
        dto.setUrlpath("showappinfo");
        model.addAttribute("appinfo",dto);
        return "backenduser/showappinfo";
    }

    /**
     * 上架
     * @param id
     * @return
     */
    @RequestMapping("/put")
    public String put(@RequestParam( "id") String id){
        if (appInfoService.putaway(id)){
            logger.info("上架成功"+id);
            return InternalResourceViewResolver.REDIRECT_URL_PREFIX+"/bu/showappinfo";
        }
        return "403";
    }
    /**
     * 下架
     * @param id
     * @return
     */
    @RequestMapping("/soldout")
    public String soldout(@RequestParam("id") String id){
      if (appInfoService.soldout(id)){
          logger.info("下架成功"+id);
          return InternalResourceViewResolver.REDIRECT_URL_PREFIX+"/bu/showappinfo";
      }
        return "403";
    }

    /**
     * 根据ID查询AppInfo信息
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/afshow")
    public String afshow(@RequestParam("id")String id,Model model){
        AppInfo appInfo= null;
        try {
            appInfo = appInfoService.selectById(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("appinfo:"+appInfo.getSoftwarename()+"》》"+appInfo.getApkname());
        model.addAttribute("appinfoshow",appInfo);
        return "backenduser/check";
    }
    /**
     * 根据ID查询AppInfo信息
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/afshowJSON"/*,produces = {"application/json;charset=UTF-8"}*/)
    @ResponseBody
    public AppInfo afshowjson(@RequestParam("id")String id,Model model){
       AppInfo appInfo=new AppInfo();
        if (null=="id"||"".equals(id)){
           // return "没有数据";
            appInfo=null;
        }else {
            try {
                appInfo= appInfoService.selectById(id);
            } catch (Exception e) {
                e.printStackTrace();
            }
            logger.info("appinfo:"+appInfo);
        }
        return appInfo;
    }


    /**
     * 初始化新增数据
     * @param appInfo
     * @return
     */
    @RequestMapping("/add")
    public String add(@ModelAttribute("appInfo") AppInfo appInfo) {

        return "backenduser/addappinfo";
    }

    /**
     * 新增APP基础信息
     * @param appInfo
     * @param rs
     * @param model
     * @return
     */
    @RequestMapping("/addSave")
    public String addSave(@Valid AppInfo appInfo, BindingResult rs,@RequestParam("logpicpath") MultipartFile logpicpath , Model model,HttpSession session) throws IOException {
        if (rs.hasErrors()){
            return "backenduser/addappinfo" ;
        }
        appInfo.setCreationdate(new Date());
        //如果没有文件上传，MultipartFile ogpicpath也不会为null,可以通过调用getsize()方法获取文件的大小来判断是否有上传文件
        if (logpicpath.getSize()>0) {
            String path=session.getServletContext().getRealPath("images");
            String fileName=logpicpath.getOriginalFilename();
            if (fileName.endsWith("jpg")||fileName.endsWith("png")) {
                File file=new File(path,fileName);
                logpicpath.transferTo(file);
            }
        }
        if (appInfoService.addAppinfo(appInfo)){
            return "redirect:/bu/showappinfo";
        }
        return "backenduser/addappinfo";
    }

    /**
     * 审核
     * @return
     */
    @RequestMapping("/check")
    public String check(@RequestParam(value = "aid",required = false)String id,
                        @RequestParam(value = "vid",required = false)String versionid,
                        Model model){
        AppInfo appInfo=null;
        AppVersion appVersion=null;
        try {
            appInfo=appInfoService.selectById(id);
            appVersion=appVersionService.selectById(versionid);
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("appInfo",appInfo);
        model.addAttribute("appVersion",appVersion);
        return "backenduser/check";
    }
    /**
     * 用来处理审核
     * @return
     */
    @RequestMapping("/checksave")
    public String checksave(AppInfo appInfo){
               logger.info("appinfo=============>>:"+appInfo.getStatus()+":"+appInfo.getId());
            if (appInfoService.updateStatus(appInfo.getStatus(),appInfo.getId())) {
               return InternalResourceViewResolver.REDIRECT_URL_PREFIX+"/bu/showappinfo";
            }
          return "backenduser/check";
    }
}

